<?php
declare (strict_types = 1);

namespace app\controller\order;

use app\BaseController;
use app\model\OrderStatus;
use Exception;
use think\Request;
use think\Response;

class Status extends BaseController
{
    protected function model(): OrderStatus
    {
        return new OrderStatus();
    }

    /**
     * 获取订单状态
     * @return Response
     */
    public function index(): Response
    {
        try {
            $oid = $this->organization;
            $result = $this->model()->where('oid', $oid)
                ->order('sort', 'desc')
                ->order('id', 'asc')->select()->toArray();
            return apiResponse(200, 'success', $result);
        } catch (Exception $e){
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        try {
            $data = $request->param();
            $oid = $this->organization;
            $data['oid'] = $oid;
            $status = $this->model()->where('oid', $oid)
                ->where('name', $data['name'])
                ->findOrEmpty();
            if (!$status->isEmpty()) {
                return apiResponse(400, '状态已存在，无法重复添加');
            }
            $this->model()->save($data);
            return apiResponse(200, '状态添加成功');
        } catch (Exception $e){
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        try {
            $data = $request->param();
            $oid = $this->organization;
            $status = $this->model()->where('oid', $oid)
                ->where('id', '<>', $id)
                ->where('name', $data['name'])
                ->findOrEmpty();
            if (!$status->isEmpty()) {
                return apiResponse(400, '状态已存在，无法重复添加');
            }
            $this->model()->where('id', $id)->update($data);
            return apiResponse(200, '状态更新成功');
        }catch (Exception $e){
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return Response
     */
    public function delete(int $id): Response
    {
        try {
            $oid = $this->organization;
            $this->model()->where('oid', $oid)
                ->where('id', $id)
                ->delete();
            return apiResponse(200, '状态删除成功');
        } catch (Exception $e){
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }
}
